package com.xyz.messagehelper.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import com.xyz.messagehelper.utils.SharePreferenceUtils
import kotlinx.android.synthetic.main.home_activity.*
import me.rosuh.filepicker.config.FilePickerManager
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.view.KeyEvent
import com.xyz.messagehelper.R
import com.xyz.messagehelper.contract.HomeContract
import com.xyz.messagehelper.presenter.HomePresenter
import com.xyz.messagehelper.utils.ActivityConctroler
import com.xyz.messagehelper.utils.Utils
import java.io.File
import java.lang.ref.WeakReference


@SuppressLint("SetTextI18n")
class HomeActivity : BaseActivity(), HomeContract.View {

    private var exitTime: Long = 0

    override fun shwowMessageTotalCount(count: Int) {
        tvTotalCount.text = "选择联系人总数：$count"
    }

    private val homePresenter = HomePresenter(this)

    override fun getLayoudResId(): Int = R.layout.home_activity


    override fun init() {
        super.init()
        ActivityConctroler.add(WeakReference(this))
        applySendSmsPermission()
        val path = SharePreferenceUtils.getString(Utils.context, "message_path", null)
        if (path != null) {
            tvFilePath.text = "选择文件路径：$path"
            homePresenter.parseFileInfo(path)
        }
        btnfilePicker.setOnClickListener {
            FilePickerManager.from(this)
                .forResult(FilePickerManager.REQUEST_CODE)
        }
        btnSmsRule.setOnClickListener {
            startActivity<MessageRulesSetActivity>()
        }
        btnClearParaInfo.setOnClickListener {
            SharePreferenceUtils.clear(this)
            toast("清理信息完成")
            ActivityConctroler.finishAll()
        }
        btnStartSendMessage.setOnClickListener {
            startActivity<SendMessageTaskActivity>()
        }
        btnSoftwareInfo.setOnClickListener {
            startActivity<SoftwareInfoActivity>()
        }
        btnOpenLoggerFile.setOnClickListener {
            val loggerFilePath =
                Utils.context.getExternalFilesDir("").path + File.separator + "taskLoggerFile.txt"
            val file = File(loggerFilePath)
            if (file.exists()) {
                Utils.openAndroidFile(this@HomeActivity,file)
            } else {
                toast("当前没有日志记录")
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        } else toast("申请权限失败")
    }

    private fun applySendSmsPermission() {
        val permissions =
            arrayOf(
                Manifest.permission.SEND_SMS, Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.READ_SMS, Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        ActivityCompat.requestPermissions(this, permissions, 0)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            FilePickerManager.REQUEST_CODE -> {
                if (resultCode == Activity.RESULT_OK) {
                    val filePaths = FilePickerManager.obtainData()
                    tvFilePath.text = "选择文件路径：${filePaths[0]}"
                    homePresenter.parseFileInfo(filePaths[0])
                } else {
                    toast("您没有选择任何文件哦~")
                }
            }
        }
    }

    private fun exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            toast("再按一次退出程序")
            exitTime = System.currentTimeMillis()
        } else {
            ActivityConctroler.finishAll()
            System.exit(0)
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit()
            return false;
        }
        return super.onKeyDown(keyCode, event)
    }

}
